const mongoose = require('mongoose')
const User = mongoose.model('User')
const Comment = mongoose.model('Comment')
const { getWechat } = require('../../wechat')
const util = require('../../libs/util')
const Movie = require('../api/movie')
const api = require('../api')
const config = require('../../config/config')
const rp = require('request-promise')

exports.guess = async (ctx, next) => {
  let url = ctx.href.replace('http://', 'https://')

  const params = await api.wechat.getSignatureAsync(url)

  await ctx.render('wechat/game', params)
}

exports.jump = async (ctx, next) => {
  const movieId = ctx.params.id
  const redirect = encodeURIComponent(config.wechat.baseUrl + '/wechat/movie/' + movieId)
  // const redirect = config.wechat.baseUrl + '/wechat/movie/' + movieId
  const url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + config.wechat.appID + '&redirect_uri=' + redirect + '&response_type=code&scope=snsapi_base&state=' + movieId + '#wechat_redirect'

  ctx.redirect(url)
}

exports.find = async (ctx, next) => {
  const code = ctx.query.code
  const options = {
    uri: 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' + config.wechat.appID + '&secret=' + config.wechat.appSecret + '&code=' + code + '&grant_type=authorization_code',
    json: true
  }
  const response = await rp(options)
  const openid = response.openid
  let user = await User.findOne({openid: openid})

  if (!user) {
    user = new User({
      openid: openid,
      password: 'imoocimooc',
      name: Math.random().toString(36).substr(2)
    })

    user = await user.save()
  }

  ctx.session.user = user
  ctx.state.user = user

  const id = ctx.params.id
  const client = getWechat()
  const data = await client.fetchAccessToken()
  const accessToken = data.access_token
  const ticketData = await client.fetchTicket(accessToken)
  const ticket = ticketData.ticket
  const url = ctx.href.replace(':8000', '')
  let params = util.sign(ticket, url)
  const movie = await Movie.searchById(id)
  const comments = await Comment
    .find({movie: id})
    .populate('from', 'name')
    .populate('reply.from reply.to', 'name')

  params.movie = movie
  params.comments = comments

  await ctx.render('wechat/movie', params)
}
